﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Interactivity;

namespace BringToFrontBehavior
{
    public class BringToFrontBehavior : Behavior<Panel>
    {
        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.Loaded += new RoutedEventHandler(AssociatedObject_Loaded);
        }
        protected override void OnDetaching()
        {
            base.OnDetaching();
            foreach (var child in AssociatedObject.Children)
            {
                child.RemoveHandler(FrameworkElement.MouseLeftButtonDownEvent, new MouseButtonEventHandler(child_MouseLeftButtonDown));
            }
        }

        void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
        {
            foreach (var child in AssociatedObject.Children)
            {
                //child.MouseLeftButtonDown += new MouseButtonEventHandler(child_MouseLeftButtonDown);
                // updated this as there is a possibility that other behaviors have marked the event as handled.
                child.AddHandler(FrameworkElement.MouseLeftButtonDownEvent, new MouseButtonEventHandler(child_MouseLeftButtonDown),true);
               
            }
        }

        void child_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            BringToFront(sender);
            
            e.Handled = true;
        }

        private void BringToFront(object sender)
        {
            Panel parent = (Panel)((FrameworkElement)sender).Parent;

            int z = getHighestValue(parent);

            for (int i = 0; i < parent.Children.Count; i++)
            {
                if (sender.Equals(parent.Children[i]))
                {
                    parent.Children[i].SetValue(Canvas.ZIndexProperty, z);
                }
            }
        }

        private int getHighestValue(Panel parent)
        {
            int highest = 0;
            foreach (var child in parent.Children)
            {
                var val = (int)child.GetValue(Canvas.ZIndexProperty);
                if (val > highest) {
                    highest = val;
                }
                child.SetValue(Canvas.ZIndexProperty, val - 1);
            }
            return highest;
        }
    }
}
